<template>
  <div class="hk-video" ref="hk" id="hk-video" :loading="loading">
    <div class="lost-video" v-if="isError">
      <p class="lost-video-text">
        视频插件加载失败
      </p>
      <p class="lost-video-text">
        <span>若视频未正常打开，请点击此处</span>
        <a-button type="link" @click="openDownload">
          下载
        </a-button>
        <span>
          并安装，并重启浏览器（推荐使用 Chrome、IE11 及以上版本）
        </span>
      </p>
      <p class="lost-video-text">
        <span>
          若已经安装过插件，请点击
        </span>
        <a-button type="link" @click="initWebControl">
          唤醒
        </a-button>
        <span>
          启动程序，并刷新当前页面
        </span>
      </p>
    </div>
  </div>
</template>

<script lang="ts" setup name="ScreenSafeVideo">
import { onMounted, onUnmounted, ref, nextTick, computed, defineProps, defineEmits, defineExpose, watch } from 'vue';
import { DeviceInfo,deviceToken } from '/@/api/safealarm/deviceInfo';
import { message } from 'ant-design-vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  deviceInfo: {
    type: Object,
    default: {}
  }
});

const emit = defineEmits(['capture', 'update:modelValue', 'initialized']); // 添加 'initialized' 事件
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
});
// 实例
const control = ref<any>({});
const loading = ref(false);
// 初始化失败
const isError = ref(false);
// 存储 key
const ezviz = ref();
// dom 节点
const hk = ref<Element>();
// 初始化完成标志
const isInitialized = ref(false);

// 下载播放器组件
const openDownload = () => {
  window.open('https://pic.hik-cloud.com/chain/download/cloudViewSetup.exe');
};

// 单点播放
const play = async () => {
  if (isError.value) return message.error('播放器连接失败,确认本地是否已安装并开启！');
  if (!isInitialized.value ||!control.value.JS_RequestInterface) {
    return message.error('播放器未初始化完成，请稍后再试！');
  }
  console.log('play 方法已加载');
  const data = {
    deviceSerial: props.deviceInfo.code, 
    channelNo: 1, 
    codeIsEncrypt: 0, 
    validateCode: '', 
    channelId: props.deviceInfo.enterpriseId, 
    channelName: props.deviceInfo.regionName, 
    storeName: props.deviceInfo.enterpriseName, 
    devType: +props.deviceInfo.type, 
    isEncrypt: false 
  };
  console.log('data 对象内容:', data);

  const argumentsPram = {
    response: {
      code: 0,
      message: null,
      data
    }
  };
  await control.value.JS_RequestInterface({
    funcName: 'StartPreview',
    arguments: encodeURI(JSON.stringify(argumentsPram))
  });
};
// 抓图
const capture = () => {
  if (isError.value) return message.error('播放器连接失败,确认本地是否已安装并开启！');
  if (!isInitialized.value ||!control.value.JS_RequestInterface) {
    return message.error('播放器未初始化完成，请稍后再试！');
    
  }
  control.value.JS_RequestInterface({
    funcName: 'CaptureJPGEx',
    arguments: encodeURI(
      JSON.stringify({
        response: {
          code: 0,
          message: null,
          data: null
        }
      })
    )
  });
};

// 创建播放器实例
const initWebControl = () => {
  console.log('初始化');
  loading.value = true;
  isError.value = false;
  let webControl: any;
  webControl = new window.WebControl({
    szPluginContainer: 'hk-video',
    iServicePortStart: 14510,
    iServicePortEnd: 14520,
    // 连接成功的回调
    cbConnectSuccess: async () => {
      control.value = webControl;
      webControl = null;
      // 监听窗口控制回调
      control.value.JS_SetWindowControlCallback({
        cbIntegrationCallBack: (data: any) => {
          // 初始化成功
          // if (data.responseMsg.eventName === 'FireInitResult') {}
          // 播放视频
          if (data.responseMsg.eventName === 'NotifyEvent') {
            // 如果没有值说明是第一次播放
            if (!modelValue.value) {
              modelValue.value = data.responseMsg.arguments.channelId;
              console.log('播放视频:', data.responseMsg.arguments.channelId);
            }
          }
          // 选中视频
          if (data.responseMsg.eventName === 'FireWndInfo') {
            // 选中视频改变选中值
            if (data.responseMsg.arguments.channelId) {
              modelValue.value = data.responseMsg.arguments.channelId;
              console.log('选中视频:', data.responseMsg.arguments.channelId);
            }
          }
          // 抓图返回 base64
          if (data.responseMsg.eventName === 'FireCaptureData') {
            emit('capture', `data:image/png;base64,${data.responseMsg.arguments.data}`);
          }
        }
      });
      // 创建视频窗口
      await control.value.JS_StartService('window', {
        dllPath: './chain/cloudTransform.dll'
      });
      // 确保 hk 元素存在且有正确的尺寸
      if (hk.value) {
        await control.value.JS_CreateWnd('hk-video', hk.value.clientWidth, hk.value.clientHeight);
      }
      loading.value = false;
      mountListener();
      initVideo();
      isInitialized.value = true;
      emit('initialized'); // 触发初始化完成事件
    },
    // 连接失败
    cbConnectError: () => {
      control.value = {};
      loading.value = false;
      isError.value = true;
      message.error('播放器连接失败,确认本地是否已安装并开启！');
    },
    // 连接断开
    cbConnectClose: (bNormalClose: boolean) => {
      control.value = {};
      loading.value = false;
      isError.value = true;
      if (!bNormalClose) message.error('连接异常断开');
    }
  });
};

// 初始化视频
const initVideo = async () => {
  const data = {
    userName: '', 
    waterMark: '0', 
    intelligenceEnable: 1, 
    motionDetectEnable: 0, 
    playBackAlarmOverlyingEnable: 0, 
    appKey: ezviz.value.appKey, 
    ezvizToken: ezviz.value.token, 
    videoLevel: 1, 
    showMainTool: 1, 
    showSubTool: 1, 
  };
  const argumentsPram = {
    type: 'chain', 
    response: {
      code: 0,
      message: null,
      data
    },
  };
  // 调用视频控件初始化方法
  await control.value.JS_RequestInterface({
    funcName: 'Init',
    arguments: encodeURI(JSON.stringify(argumentsPram))
  });
};

// 挂载监听事件
const mountListener = () => {
  window.addEventListener('scroll', resizeVideo);
  window.addEventListener('resize', resizeVideo);
  window.addEventListener('unload', destoryVideo);
  window.addEventListener('pagehide', hiddenVideo);
};

// 卸载监听事件
const unMountListener = () => {
  window.removeEventListener('scroll', resizeVideo);
  window.removeEventListener('resize', resizeVideo);
  window.removeEventListener('unload', destoryVideo);
  window.removeEventListener('pagehide', hiddenVideo);
  destoryVideo();
};

// 隐藏视频组件
const hiddenVideo = () => {
  if (isError.value) return;
  control.value.JS_HideWnd();
};

// 显示视频组件
const showVideo = () => {
  if (isError.value) return;
  control.value.JS_ShowWnd();
};

// 销毁视频组件
const destoryVideo = async () => {
  hiddenVideo();
  await control.value.JS_HideWnd();
  // 销毁视频控件
  await control.value.JS_DestroyWnd();
  await control.value.JS_StopService('window');
  await control.value.JS_Disconnect();
};

// 重置视频
const resizeVideo = () => {
  if (control.value && hk.value) {
    control.value.JS_Resize(hk.value.clientWidth, hk.value.clientHeight);
  }
};

onMounted(async () => {
  loading.value = true;
  await nextTick();
  // 获取播放器所需 token
  const tokenData = await deviceToken();
  console.log('tokenData', tokenData);
  ezviz.value = tokenData;
  // 确保 hk 元素已经挂载
  await new Promise(resolve => setTimeout(resolve, 100));
  initWebControl();
});

// 页面卸载清除播放组件
onUnmounted(unMountListener);

defineExpose({
  play,
  capture,
  hiddenVideo,
  showVideo
});
</script>

<style lang="less" scoped>
.hk-video {
  flex: 1;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  width:600px;
  height: 600px;
  .lost-video {
    text-align: center;
    color: #000;
    font-weight: bold;

    img {
      vertical-align: middle;
    }

    .lost-video-text {
      display: flex;
      align-items: center;
      justify-content: center;

      .ant-btn {
        line-height: inherit;
        margin: 0 5px;
      }
    }
  }
}
</style>